package top.yiwyn.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.yiwyn.common.ResultBean;
import top.yiwyn.service.MyUserDetailsService;
import top.yiwyn.service.UserService;
import top.yiwyn.util.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    MyUserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenUtil jwtTokenUtil;


    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Override
    public ResultBean login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return ResultBean.fail("用户名或密码错误");
        }

//        更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


//        生成token
        Map<String, Object> tokenMap = new HashMap<>();

        String token = jwtTokenUtil.generateToken(userDetails);
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return ResultBean.succ("登录成功", tokenMap);
    }
}
